 
package com.ctsi.commons.util.json;

import com.ctsi.commons.util.UtilFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
 

 

/**json对象，用来区分string */
 
public final class JSON {

 

    /**
     * 建立json对象，从stream,编码为 UTF-8.
     * 
     * @param inStream
     * @return a <code>JSON</code> instance
     * @throws IOException
     */
    public static JSON from(InputStream inStream) throws IOException {
     
        String jsonString;
		try {
			jsonString = UtilFile.readString(inStream, StandardCharsets.UTF_8);
		} catch (Exception e) {
			if(e instanceof IOException)
				throw (IOException)e;
            throw new IOException(e);
		}
        return from(jsonString);
    }

    /**
     *对象转化为json
     * 
     * @param object
     * @return a <code>JSON</code> instance
     * @throws IOException
     */
    public static JSON from(Object object) throws IOException {
       
        try {
            return from(JsonUtil.toJson(object));
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    /**
     * 从reader读取
     * 
     * @param reader
     * @return a <code>JSON</code> instance
     * @throws IOException
     */
    public static JSON from(Reader reader) throws IOException {
       
        String jsonString = UtilFile.readToString(reader);
        return from(jsonString);
    }

    /**
     * 包装String为对象
     * 
     * @param jsonString
     * @return a <code>JSON</code> instance
     */
    public static JSON from(String jsonString) {
      

        return new JSON(jsonString);
    }

    private final String jsonString;

    private JSON(String jsonString) {
        this.jsonString = jsonString;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof JSON) {
            return jsonString.equals(((JSON)obj).jsonString);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return jsonString.hashCode();
    }

    /**
     * Converts this <code>JSON</code> object to the specified type.
     * 
     * @param targetClass
     * @return an object of the specified type
     * @throws IOException
     */
    public <T> T toObject(Class<T> targetClass) throws IOException {
   
        try {
        	return JsonUtil.json2Bean(jsonString, targetClass);
 
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public String toString() {
        return jsonString;
    }
}
